using Fadd.Parser.SimpleSQL.Tokens;

namespace Fadd.Parser.SimpleSQL.ParseTreeTokens
{
    /// <summary>
    /// Parsing a property
    /// </summary>
    public class PropertyToken : ParseTreeToken
    {
        /// <summary>
        /// Check if the current position is the start of this token
        /// </summary>
        /// <returns>true if our token is the next one.</returns>
        public override bool Match(Tokenizer tokenizer, ParseTree tree)
        {
            // Cant be a condition or a property that was last.
            if (tree.Current is Where && (tree.LastInserted is IConditional || tree.LastInserted is Tokens.Property))
                return false;

            char peek = tokenizer.Peek(Parser.WhiteSpaces);
            return char.IsLetterOrDigit(peek) || peek == '*';
        }

        /// <summary>
        /// Parses the data in the specified <see cref="Tokenizer"/>.
        /// </summary>
        /// <param name="tokenizer">The <see cref="Tokenizer"/> containing the data to parse.</param>
        /// <param name="tree"><see cref="ParseTree"/> that is being built..</param>
        /// <returns>true if more tokens can be parsed on the current leaf; false if we should continue to next leaf (parse no more children).</returns>
        public override bool Parse(Tokenizer tokenizer, ParseTree tree)
        {
            tokenizer.Ignore(Parser.WhiteSpaces);
            string propertyName = string.Empty;
            while (char.IsLetterOrDigit(tokenizer.Peek()) || tokenizer.Peek() == '*')
                propertyName += tokenizer.Read();

            tree.Add(new Tokens.Property(propertyName));
            return true;
        }
    }
}
